<?php

namespace App\Http\Controllers;

use App\Http\Requests\GoodController\GoodShowRequest;
use App\Http\Resources\GoodResource;
use App\Models\Good;
use Illuminate\Http\Request;

class GoodController extends Controller
{
    public function index(Request $request)
    {
        $from = [
            'name' => $request->get('name') ? $request->get('name') : '',
            'page' => $request->get('page') ? $request->get('page') : 1,
        ];

        $wheres[] = ['id', '>=', 1];
        $wheres[] = ['status', '=', 1];
        if ($from['name']) {
            $wheres[] = ['name', 'like', $from['name'] . '%'];
        }

        $good = Good::where($wheres)->orderBy('id', 'desc')->paginate(20, $columns = ['id', 'name', 'u_unit_price', 'small_image', 'big_image'], $pageName = 'page', $from['page']);
        foreach ($good as $value) {
            $value->big_image = config('app.image_url') . $value->big_image;
            $value->small_image = config('app.image_url') . $value->small_image;
        }

        return GoodResource::collection($good);
    }

    public function show(GoodShowRequest $request)
    {
        $id = $request->input('id');

        $good = Good::where('id', $id)->first();
        if (! $good) {
            return $this->error(500, '商品不存在');
        }

        $good->big_image = config('app.image_url') . $good->big_image;
        $good->small_image = config('app.image_url') . $good->small_image;

        return new GoodResource($good);
    }
}
